package ee.ut.math.chess.hadoop;

import java.util.List;

import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import ee.ut.math.chess.base.model.Move;
import ee.ut.math.chess.base.model.chesspiece.ChessPiece;
import ee.ut.math.chess.game.model.Game;

@SuppressWarnings("unused")
public class Map extends Mapper<Text, BytesWritable, Text, BytesWritable>{
	
	private Game game; 
	protected void setup(Context context) throws java.io.IOException ,InterruptedException {
		
	}
	
	protected void map(Text key, BytesWritable gameInBytes, Context context) throws java.io.IOException ,InterruptedException {
		/*//DUMMY implementation
		LongWritable val = new LongWritable(5L);
		int n = 3397;
		double sqrt = Math.pow(n, 0.5);
    	
		//define content of map
    	long start = 2, end = 2;
    	for (int i = 0 ; i < val.get(); i++) {
    		start = end;
    		end = (long) (sqrt / val.get() * (i+1));
    		context.write(new Text(start + ""), new Text(end + ""));
    	}*/
		try {
            game = HadoopManager.getGameFromBytes(gameInBytes.getBytes());
        }catch (ClassNotFoundException e) {
            return;
        }
        for (int i=0; i < 8; i++) {
            for (int j=0; j <8; j++) {
                ChessPiece chessPiece = game.getBoard().getChessPiece(i, j);
                if (chessPiece != null && chessPiece.getColor() == game.getWaitingForPlayer()) {
                    List<Move> legalMoves = chessPiece.getLegalMoves(i, j, game, false);
                    for (Move move : legalMoves) {
                        context.write(new Text(move.toString()), gameInBytes);
                    }
                }
            }
        }
	}
}
